<?php
/**
 * Created by PhpStorm.
 * User: 郑合达
 * Date: 2019/1/22
 * Time: 17:23
 */

namespace app\admin\controller;


use app\model\AppUserModel;
use app\model\EquipmentModel;
use think\Controller;
class Equipment extends Common
{




    /*
     * 录音
     */
    public function  luyin(){
        $getData=input('post.');
        $expire_time= $this->expire_time($getData['imei']);
        //判断设备是否过期
        if($expire_time<=time()){
            $res['code']=203;
            $res['result']=['msg'=>'设备已过期'];
            return $res;
        }
        $arr = array('token'=>'4d9262b1a5da42779110baa9df648743');
        $url="http://api.huixun.me/open/record/{$getData['imei']}?token=4d9262b1a5da42779110baa9df648743";
//        $url = 'http://teashop.obay.vip/mobile/Index/postTest';
        $data=post_json_data($url,json_encode($arr));
        $data['result']=json_decode($data['result'],true);
        return $data;
    }

    /**
     * @return array
     */
    public function  dianhua(){
        $getData=input('post.');
        $expire_time= $this->expire_time($getData['imei']);
        //判断设备是否过期
        if($expire_time<=time()){
            $res['code']=203;
            $res['result']=['msg'=>'设备已过期'];
            return $res;
        }
        $arr = array('token'=>'4d9262b1a5da42779110baa9df648743');
        $url="http://api.huixun.me/open/telephone/{$getData['imei']}?token=4d9262b1a5da42779110baa9df648743&phone={$getData['phone']}&type={$getData['type']}";
//        $url = 'http://teashop.obay.vip/mobile/Index/postTest';
        $data=post_json_data($url,json_encode($arr));
        $data['result']=json_decode($data['result'],true);
        return $data;
    }
    /*
     * 录音通话页面
     */
    public function luyin_view()
    {
        $getData=input();
        $data['imei']=$getData['imei'];
        $url="http://api.huixun.me/open/list/voice?imei={$getData['imei']}&token=4d9262b1a5da42779110baa9df648743&orderBy=desc";
        $list = $this->curl($url);

        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['createTime']=$v['createTime']/1000;

            $list['data'][$k]['attrJson']="https://file.huixun.me/".json_decode($v['attrJson'],true)['url'];
        }
        $data['data']=$list['data'];
        return view('luyin_view',$data);
    }



    /**
     * 模拟post进行url请求
     * @param string $url
     * @param array $post_data
     */
    function request_post($url = '', $post_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);

        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }
    /*
     * 注册设备页面
     */
    public function reg_equipment()
    {

        $where =[];
        $whe=$this->equs();
        if ($whe){
            $where=['name'=>['in',$whe]];
        }
        $outtime=input('get.outtime');
        $time=[
            '1'=>['7天内过期',time()+604800,time()],
            '2'=>['60天内过期',time()+5184000,time()],
            '3'=>['已过期',time(),0],
        ];
        $start_time=0;$end_time=99999999999;
        if (isset($outtime)){
                $start_time=$time[$outtime][2];
                $end_time=$time[$outtime][1];
        }
        $data['data']=EquipmentModel::where($where)->whereTime('expire_time', 'between', [$start_time, $end_time])//筛选时间
                      ->paginate(null,false,['query'=>request()->param()]);

        foreach ($data['data'] as $k=>$v){
            if ($v['equ_user']!=0){//设备使用者
                $getAppUser=AppUserModel::find($v['equ_user']);
                $data['data'][$k]['a_u_nickname']=$getAppUser->nickname;
            }

        }

        return view('reg_equipment',$data);

    }
    /*
     * 设备新增/编辑
     */
    public function add()
    {

        $getData = input('get.');
        $data=[];
        if (isset($getData['id'])){
            $data['data']=$getEqu= EquipmentModel::find($getData['id']);//获取该管理员信息
            if ($getEqu->equ_user!=0){
                $this->error('已绑定设备不可修改');
            }
        }
        return view('add',$data);//新增页面
    }
    /*
     * 设备添加/修改
     */
    public function addData()
    {
        $getData = input('post.');
        $expire_time=strtotime($getData['expire_time']);
        if($expire_time===false) {
            $expire_time=time();
        }
        $getData['expire_time']=$expire_time;
        if (isset($getData['id'])){//修改
            sole('gps_equipment',['name'=>$getData['name']],['id',$getData['id']]);//判断修改账号是否存在
            $setDatabase=EquipmentModel::update($getData);
        }else{//新增
            sole('gps_equipment',['name'=>$getData['name']]);//判断账号是否存在
            $setDatabase=EquipmentModel::insert($getData);
        }
        return setDatabase($setDatabase);
    }
    /*
    * 删除管理员
    */
    public function del(){
        $postData = input('post.');
        $data['data']=$getEqu= EquipmentModel::find($postData['id']);//获取该管理员信息
        if ($getEqu->equ_user!=0){
            $this->error('已绑定设备不可修改');
        }
        $delRole = EquipmentModel::destroy($postData['id']);
        return setDatabase($delRole);
    }
    /**
     * @return \think\response\View
     * 设备管理页面（全部）
     */
    public function equipment(){
        return view('equipment');
    }

    /*
     * 导出设备
     */
    public function export(){
//      dump($user_id);die();
        $outtime=input('get.outtime');
        $time=[
            '1'=>['7天内过期',time()+604800,time()],
            '2'=>['60天内过期',time()+5184000,time()],
            '3'=>['已过期',time(),0],
        ];
        $start_time=0;
        $end_time=99999999999;
        if ($outtime!=''){
            $start_time=$time[$outtime][2];
            $end_time=$time[$outtime][1];
        }
        $data =EquipmentModel::field('*')
           -> whereTime('expire_time', 'between', [$start_time, $end_time])//筛选时间
            ->order('id')->select();
//         dump($data);die();
        //表头
        $header = ['序号','设备名称','设备号（IMEI）','到期时间'];
        //用于遍历的二维数组
        $result_data=array();
        for($i=0;$i<count($data);$i++){
            $new = array();
            $new[] = $i+1;
            $new[] =  $data[$i]['nickname'];
            $new[] =  'IMEI:'.$data[$i]['name'];
            $new[] =  date('Y年m月d日',$data[$i]['expire_time']);
            array_push($result_data,$new);
        }
        //$filename 文件名
        $filename = "设备".date("Y/m/d");
//        ExcelModel::getExcelFile(NULL,$header,$result_data,$filename,30);
        export($result_data, $header, $filename);
    }
    /*
     * 查询到期时间
     */
    public function expire_time($imei){
        $expire_time =EquipmentModel::where('name',$imei)->value('expire_time');
     return $expire_time;
    }
    /**
     * @param $url   接口连接的地址
     * @return mixed
     *  转接接口的方法
     */
    public function curl($url){
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);

        $data=json_decode($output,true);//$data就是最终的数据 而且已经转换成了数组
        return $data;
    }
}